package jpf.nextsearch.ds.manager.impl;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jpf.nextsearch.base.GenericObject;
import jpf.nextsearch.ds.dao.HostDao;
import jpf.nextsearch.ds.manager.HostManager;
import jpf.nextsearch.ds.model.HostVO;
import jpf.nextsearch.exception.DataAccessException;
import jpf.nextsearch.util.validation.ValidationTypes;
import jpf.nextsearch.util.validation.base.ValidatorManager;

/**
 * @author <a href="mailto:jacek.pruszkowski@gmail.com">Jacek Pruszkowski</a>
 * 
 */
public class HostManagerImpl extends GenericObject implements HostManager {

	private HostDao hostDao;

	private ValidatorManager validatorManager;

	@Override
	public List<HostVO> getAllHosts() throws DataAccessException {
		if (isLoggingDebug()) {
			getLogger().debug(" -> getAllHosts");
		}
		try {
			return getHostDao().getAll();
		} catch (Exception e) {
			if (isLoggingError()) {
				getLogger().error("Error occoured while getting all Hosts", e);
			}
			throw new DataAccessException("Error occoured while getting all Hosts", e);
		}
	}

	@Override
	public void importHostsFromFile(String path) throws Exception {
		if (isLoggingDebug()) {
			getLogger().debug(" -> importHostsFromFile");
		}		
		BufferedReader reader = new BufferedReader(new FileReader(path));
		Date now = new Date();

		List<HostVO> newHosts = new ArrayList<HostVO>(500);
		String line = null;

		while ((line = reader.readLine()) != null) {
			line = line.trim();

			if (!getValidatorManager().isValueValid(line, ValidationTypes.IPV4)) {
				if (isLoggingError()) {
					getLogger().error("Invalid ipv4 address: " + line);
				}
				continue;
			}
			HostVO host = new HostVO();
			host.setImportDate(now);
			host.setIp(line);
			newHosts.add(host);
			if (isLoggingDebug()) {
				getLogger().debug("host with ip " + line + " will be imported");
			}
		}
		if (isLoggingDebug()) {
			getLogger().debug("Saving new hosts list");
		}
		getHostDao().saveOrUpdateAll(newHosts);
		
		if (isLoggingDebug()) {
			getLogger().debug("Removing old hosts list");
		}
		int count = getHostDao().removeHostsImportetBefore(now);
		if (isLoggingDebug()) {
			getLogger().debug("Removed " + count + " hosts");
		}

	}

	public void setValidatorManager(ValidatorManager validatorManager) {
		this.validatorManager = validatorManager;
	}

	public ValidatorManager getValidatorManager() {
		return validatorManager;
	}

	public void setHostDao(HostDao hostDao) {
		this.hostDao = hostDao;
	}

	public HostDao getHostDao() {
		return hostDao;
	}

}
